﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;
using System.Text;

namespace PowerBooking.RSE.Domain.Behaviors
{
    public class ErrorHandler : IErrorHandler
    {
        public readonly Func<Exception, bool> FnHandleError;
        public readonly Func<Exception, object> FnGetFaultDetails;

        public ErrorHandler(Func<Exception, bool> fnHandleError, Func<Exception, object> fnGetFaultDetails)
        {
            FnHandleError = fnHandleError;
            FnGetFaultDetails = fnGetFaultDetails;
        }

        public bool HandleError(Exception error)
        {
            if (FnHandleError == null)
                return false;
            return FnHandleError(error);
        }

        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            var isJson = true;
            var context = WebOperationContext.Current;
            if (null != context && null != context.OutgoingResponse && null != context.OutgoingResponse.Format)
                isJson = context.OutgoingResponse.Format.Value == WebMessageFormat.Json;
            var faultDetails = null == FnGetFaultDetails ? null : FnGetFaultDetails(error);
            var bodyWriter = new FaultBodyWriter(faultDetails, isJson);
            fault = Message.CreateMessage(version, string.Empty, bodyWriter);
            var bodyFormatProperty = new WebBodyFormatMessageProperty(isJson ? WebContentFormat.Json : WebContentFormat.Xml);
            fault.Properties[WebBodyFormatMessageProperty.Name] = bodyFormatProperty;
            if(isJson)
                context.OutgoingResponse.ContentType = "application/json";
        }
    }
}
